import AspectPro from '@huolala/aspectpro';
import { HttpClient } from '@ohos/httpclient';
import { TestClass1 } from '../model/TestClass1';
import { MyEventListener, MyInterceptor } from '../model/TestHttpClient';


export const TAG = "Aop_Demo"

export function testHookHttpClientBuild() {
  // 1.hook HttpClient#Builder()#build()
  AspectPro.hookMethod({
    target: HttpClient,
    methodNameOrProperty: 'Builder',
    beforeFn: (context, args) => {
      /**
       * todo
       * context:是函数执行上下文，类型为 HttpClient.Builder，
       * ets 暂时不支持typeof， 因此此处在.ts文件中hook
       */
      const builderContext = context as InstanceType<typeof HttpClient.Builder>;
      builderContext._eventListeners = new MyEventListener();
      builderContext.addInterceptor(new MyInterceptor());
    },
    propertyMethodNameOrType: 'build'
  })
}


export function baseHook() {
  AspectPro.addAfter(TestClass1, "b", () => {
    console.log("1.AspectPro add after ---- TestClass1#b() ，do your business ...");
  })


  AspectPro.replace(TestClass1, "c", (origin: Function, ...args: object[]) => {

    let changedArgs = [...args]
    // changedArgs[0] = new String("string")

    //改变入参
    const result: string = origin("string")

    // const result: string = origin("a")

    console.log("1.AspectPro replace ---- TestClass1#c() ，do your business ..."
      + "result:" + result);
    //可以改变结果
    return result
  })
  // hook TestClass1#a()
  AspectPro.hookMethod({
    target: TestClass1,
    methodNameOrProperty: 'a',
    afterFn: () => {
      console.log("AspectPro hookedMethod-> afterFn ---- TestClass1#a() ，do your business ...");
    }
  })

}



